import { ExceptionFilter, Catch, UnauthorizedException, Response, HttpStatus } from '@nestjs/common';
import { ApiResponse, ResponseCode } from '../common/interfaces/response.interface';

@Catch(UnauthorizedException)
export class UnauthorizedFilter implements ExceptionFilter {
  catch(exception: UnauthorizedException, host: any) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    
    // 返回统一的JSON格式而不是重定向
    const responseBody: ApiResponse<null> = {
      code: ResponseCode.UNAUTHORIZED,
      message: '未授权访问，请先登录',
      timestamp: Date.now(),
    };
    
    response.status(HttpStatus.UNAUTHORIZED).json(responseBody);
  }
}